document.addEventListener('DOMContentLoaded', function () {
    // 获取数量增加和减少的按钮
    const foodList = document.querySelectorAll('.foodList');
    const decreaseBtns = document.querySelectorAll('.decrease');
    const increaseBtns = document.querySelectorAll('.increase');
    const quantities = document.querySelectorAll('.quantity');
    const footerQty = document.querySelector('.footerQty');
    const footerPrice = document.querySelector('.footerInf div');

    // 获取每个商品对应的价格（从 span.price 中提取）
    const prices = Array.from(document.querySelectorAll('.price')).map(span => {
        return parseFloat(span.innerText);
    });

    // 更新购物车数量和总价
    function updateCart() {
        let totalQty = 0;
        let totalPrice = 0;

        quantities.forEach((quantity, index) => {
            const qty = parseInt(quantity.innerText);
            totalQty += qty;
            totalPrice += qty * prices[index];
        });

        // 更新购物车中的商品数量
        footerQty.innerText = totalQty;

        // 更新购物车的总价（包括配送费3元）
        footerPrice.innerText = `¥${(totalPrice + 3).toFixed(2)}`;
    }

    // 处理减少按钮点击事件
    decreaseBtns.forEach((btn, index) => {
        btn.addEventListener('click', () => {
            let qty = parseInt(quantities[index].innerText);
            if (qty > 0) {
                quantities[index].innerText = qty - 1;
                updateCart();
            }
        });
    });

    // 处理增加按钮点击事件
    increaseBtns.forEach((btn, index) => {
        btn.addEventListener('click', () => {
            let qty = parseInt(quantities[index].innerText);
            quantities[index].innerText = qty + 1;
            updateCart();
        });
    });

    // 初始化购物车
    updateCart();
});


function toOrder(){
    const foodItems = document.querySelectorAll('.foodList');
    const selectedItems = [];

    foodItems.forEach(item => {
        const name = item.querySelector('.foodInfo h3').innerText;
        const price = parseFloat(item.querySelector('.price').innerText);
        const quantity = parseInt(item.querySelector('.quantity').innerText);
        const imgSrc = item.querySelector('img').getAttribute('src'); // 获取图片路径

        if (quantity > 0) {
            selectedItems.push({ name, price, quantity, imgSrc }); // 加入图片路径
        }
    });

    // 存入 sessionStorage（在下一个页面再从中取出）,对比原版localStorage生命周期更合理
    sessionStorage.setItem('selectedItems', JSON.stringify(selectedItems));

    // 页面跳转
    window.location.href = 'confirm.html';
}